# post请求
# 响应数据为json数据
import json

import requests

if __name__ == '__main__':
    # 请求url
    url = 'https://fanyi.baidu.com/sug'
    # post参数
    word = input('enter a word:')
    date = {'kw': word}
    # 请求头
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
    }
    # 请求发送
    response = requests.post(url=url, data=date, headers=headers)
    # 获取返回的json,确认响应类型是json才能用json
    dic_obj = response.json()
    print(dic_obj)
    # 保存
    fileName = word + '.json'

    with open(fileName, 'w', encoding='utf-8') as fp:
        #保存json文件，拿到的中文不能用ascii编码
        json.dump(dic_obj, fp=fp, ensure_ascii=False)

    print('over')
